package com.guiwu.controller;

import com.guiwu.entity.Category;
import com.guiwu.entity.User;
import com.guiwu.entity.Item;
import com.guiwu.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class DashboardController {
    @Autowired
    private ItemService itemService;

    @GetMapping("/dashboard")
    public String dashboard(@AuthenticationPrincipal User user, Model model) {
        // 获取用户的所有物品
        List<Item> items = itemService.getAllItemsByUser(user.getId());

        // 获取统计信息
        BigDecimal totalAssets = itemService.getTotalAssets(user.getId());
        BigDecimal averageDailyPrice = itemService.getAverageDailyPrice(user.getId());
        List<Category> categories = itemService.getCategoriesByUser(user.getId());

        model.addAttribute("items", items);
        model.addAttribute("totalAssets", totalAssets);
        model.addAttribute("averageDailyPrice", averageDailyPrice);
        model.addAttribute("categories", categories);
        model.addAttribute("user", user);
        return "dashboard";
    }

    @GetMapping("/items")
    public String items(@AuthenticationPrincipal User user,
                       @RequestParam(required = false) Long categoryId,
                       @RequestParam(required = false) String search,
                       Model model) {
        List<Item> items;
        if (search != null && !search.trim().isEmpty()) {
            items = itemService.searchItems(user.getId(), search.trim());
        } else if (categoryId != null) {
            items = itemService.getItemsByCategory(user.getId(), categoryId);
        } else {
            items = itemService.getAllItemsByUser(user.getId());
        }

        // 获取统计信息
        BigDecimal totalAssets = itemService.getTotalAssets(user.getId());
        BigDecimal averageDailyPrice = itemService.getAverageDailyPrice(user.getId());
        List<Category> categories = itemService.getCategoriesByUser(user.getId());

        model.addAttribute("items", items);
        model.addAttribute("totalAssets", totalAssets);
        model.addAttribute("averageDailyPrice", averageDailyPrice);
        model.addAttribute("categories", categories);
        model.addAttribute("selectedCategory", categoryId);
        model.addAttribute("searchKeyword", search);
        model.addAttribute("user", user);
        return "items";
    }
} 